<template>
  <div class="w-full lg:w-[90%] mx-auto">
    <!-- 一级分类 -->
    <div class="flex flex-nowrap overflow-x-auto mb-4 scrollbar-hide">
      <a
        v-for="(item, index) in mainCategoryList"
        :key="index"
        :href="getCategoryUrl(item.name)"
        @click.prevent="handleMainCategoryClick(item.name)"
        :class="[
          'mr-5 whitespace-nowrap text-lg font-bold cursor-pointer transition-all duration-200',
          selectedMainCategoryName === item.name
            ? 'text-primary border-b-4 border-primary'
            : 'text-gray-500 hover:text-gray-700',
        ]"
      >
        {{ item.name }}
      </a>
    </div>
    
    <!-- 二级分类 -->
    <div class="relative mb-4">
      <svg-icon
        v-show="showLeftArrow"
        name="arrow-left"
        class="absolute left-0 top-1/2 -translate-y-1/2 cursor-pointer hover:opacity-80 transition-opacity"
        fill="var(--primary-color)"
        @click="scrollSubCategoryLeft"
      />
      <div
        ref="subCategoryContainer"
        class="flex flex-nowrap overflow-x-auto scrollbar-hide sub-category-container"
        :style="{ 
          width: 'calc(100% - 26px)', 
          scrollBehavior: 'smooth', 
          '-webkit-overflow-scrolling': 'touch' 
        }"
        @scroll="handleSubCategoryScroll"
      >
        <a
          v-for="(item, index) in subCategoryList"
          :key="index"
          :href="getSubCategoryUrl(selectedMainCategoryName, item.name)"
          @click.prevent="handleSubCategoryClick(item.name)"
          :class="[
            'mr-2 whitespace-nowrap text-lg cursor-pointer transition-all duration-200 rounded-3xl pt-1 pb-1 pl-3 pr-3',
            selectedSubCategoryName === item.name
              ? 'border-primary bg-primary text-white'
              : 'border border-gray-300 text-gray-500 hover:text-gray-700 bg-white',
          ]"
        >
          {{ item.name }}
        </a>
        <!-- 加载状态指示器 -->
        <div
          v-if="subCategoryLoading"
          class="mr-2 whitespace-nowrap text-lg rounded-3xl pt-1 pb-1 pl-3 pr-3 border border-gray-300 text-gray-500 bg-white flex items-center"
        >
          <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-500 mr-2"></div>
          Loading...
        </div>
      </div>
      <svg-icon
        name="arrow-right"
        class="absolute right-0 top-1/2 -translate-y-1/2 cursor-pointer hover:opacity-80 transition-opacity"
        fill="var(--primary-color)"
        @click="scrollSubCategoryRight"
      />
    </div>

    <!-- 成本分类 -->
    <div class="flex flex-nowrap overflow-x-auto mb-4 scrollbar-hide">
      <a
        v-for="(item, index) in costCategoryList"
        :key="index"
        :href="getCostUrl(item.name)"
        @click.prevent="handleCostCategoryClick(item.name)"
        :class="[
          'mr-2 whitespace-nowrap text-lg cursor-pointer transition-all duration-200 rounded-3xl pt-1 pb-1 pl-3 pr-3',
          selectedCost === item.name
            ? 'border-primary bg-primary text-white'
            : 'border border-gray-300 text-gray-500 hover:text-gray-700 bg-white',
        ]"
      >
        {{ item.name }}
      </a>
    </div>

    <!-- 应用列表 -->
    <BusinessAppList
      :appList="appList"
      :selectedMainCategoryName="selectedMainCategoryName"
      :selectedSubCategoryName="selectedSubCategoryName"
      ad-slot="mainDisplay1"
    />

    <!-- 底部观察点 - 用于无限滚动 -->
    <div ref="bottomObserverPoint" class="h-[1px] w-full"></div>
  </div>
</template>

<script setup>

// 常量定义
const DEFAULT_MAIN_CATEGORY = "Trending";
const DEFAULT_SUB_CATEGORY = "All";
const DEFAULT_COST_FILTER = "All";
const APP_LIST_PAGE_SIZE = 12;
const SUB_CATEGORY_PAGE_SIZE = 10;
const SCROLL_BUFFER = 20; // 增加缓冲值，提高触发灵敏度
const DEBOUNCE_DELAY = 100; // 防抖延迟，避免频繁触发

// 路由和查询参数处理
const route = useRoute();
const router = useRouter();
const { category, subCategory, cost } = route.query;

// 服务端获取初始数据
const { data: serverData } = await useAsyncData('initialData', async () => {
  // 1. 获取一级分类
  const mainCategories = await $fetch("/api/category/mainCategory")
    .then(res => res?.data || [])
    .catch(() => []);
  
  // 确定初始一级分类
  const initialMainCategory = mainCategories.find(cat => cat.name === category) 
    || mainCategories[0] 
    || { name: DEFAULT_MAIN_CATEGORY };
  
  // 2. 获取对应二级分类
  const subCategories = initialMainCategory.name 
    ? await $fetch(`/api/category/${encodeURIComponent(initialMainCategory.name)}?subCategoryPageSize=${SUB_CATEGORY_PAGE_SIZE}&subCategoryPageCurrent=1`)
        .then(res => res?.data || [])
        .catch(() => [])
    : [];
  
  // 确定初始二级分类
  const initialSubCategory = subCategories.find(sub => sub.name === subCategory)
    ? subCategory
    : DEFAULT_SUB_CATEGORY;
  
  // 3. 获取初始应用列表
  const apps = initialMainCategory.name
    ? await $fetch(
        `/api/category/${encodeURIComponent(initialMainCategory.name)}/${encodeURIComponent(initialSubCategory)}?` +
        `cost=${cost || DEFAULT_COST_FILTER}&appListPageSize=${APP_LIST_PAGE_SIZE}&appListPageCurrent=1`
      ).then(res => res?.data || [])
        .catch(() => [])
    : [];
  
  return {
    mainCategories,
    subCategories,
    apps,
    initialMainCategory,
    initialSubCategory
  };
});

// 响应式数据 - 从服务端数据初始化
const mainCategoryList = ref(serverData.value?.mainCategories || []);
const subCategoryList = ref(serverData.value?.subCategories || []);
const appList = ref(serverData.value?.apps || []);
const showLeftArrow = ref(false);
const subCategoryLoading = ref(false);
const hasMoreSubCategory = ref(true);
const selectedMainCategoryName = ref(serverData.value?.initialMainCategory?.name || DEFAULT_MAIN_CATEGORY);
const selectedSubCategoryName = ref(serverData.value?.initialSubCategory || DEFAULT_SUB_CATEGORY);
const selectedCost = ref(cost || DEFAULT_COST_FILTER);

// 分页相关
const appListPageCurrent = ref(1);
const subCategoryPageCurrent = ref(1);
const subCategoryContainer = ref(null);
const bottomObserverPoint = ref(null);

// 引用
let appListObserver = null;
let scrollTimeout = null;

// 成本分类列表（固定数据）
const costCategoryList = ref([
  { name: "All" },
  { name: "Free" },
  { name: "Free Trial" },
  { name: "Paid" },
]);

// API 调用函数
const fetchSubCategories = async (categoryName, pageCurrent = 1, pageSize = SUB_CATEGORY_PAGE_SIZE) => {
  if (!categoryName) return [];
  
  const data = await $fetch(
    `/api/category/${encodeURIComponent(categoryName)}?subCategoryPageSize=${pageSize}&subCategoryPageCurrent=${pageCurrent}`
  );
  return data?.data || [];
};

const fetchAppList = async (categoryName, subCategoryName, pageCurrent = 1) => {
  if (!categoryName) return [];
  
  const data = await $fetch(
    `/api/category/${encodeURIComponent(categoryName)}/${encodeURIComponent(subCategoryName)}?` +
    `cost=${selectedCost.value}&appListPageSize=${APP_LIST_PAGE_SIZE}&appListPageCurrent=${pageCurrent}`
  );
  return data?.data || [];
};

// 事件处理函数
const handleMainCategoryClick = async (categoryName) => {
  if (selectedMainCategoryName.value === categoryName) return;
  
  // 记录事件
  logEvent("Click_Tag", {
    tag: `${categoryName}/${selectedSubCategoryName.value}/${selectedCost.value}`,
  });
  
  // 更新路由
  await router.push({
    query: {
      ...route.query,
      category: categoryName,
      subCategory: DEFAULT_SUB_CATEGORY
    }
  });
  
  // 更新状态
  selectedMainCategoryName.value = categoryName;
  selectedSubCategoryName.value = DEFAULT_SUB_CATEGORY;
  
  // 重置二级分类状态并加载新数据
  resetSubCategoryState();
  const newSubCategories = await fetchSubCategories(categoryName);
  subCategoryList.value = newSubCategories;
  
  // 加载对应应用列表
  appList.value = await fetchAppList(categoryName, DEFAULT_SUB_CATEGORY);
  appListPageCurrent.value = 1;
  
  // 确保DOM更新后重新检查滚动位置
  nextTick(() => {
    checkSubCategoryScrollPosition();
  });
};

const handleSubCategoryClick = async (subCategoryName) => {
  if (selectedSubCategoryName.value === subCategoryName) return;
  
  // 记录事件
  logEvent("Click_Tag", {
    tag: `${selectedMainCategoryName.value}/${subCategoryName}/${selectedCost.value}`,
  });
  
  // 更新路由
  await router.push({
    query: {
      ...route.query,
      subCategory: subCategoryName
    }
  });
  
  // 更新状态
  selectedSubCategoryName.value = subCategoryName;
  
  // 加载对应应用列表
  appList.value = await fetchAppList(selectedMainCategoryName.value, subCategoryName);
  appListPageCurrent.value = 1;
};

const handleCostCategoryClick = async (costValue) => {
  if (selectedCost.value === costValue) return;
  
  // 记录事件
  logEvent("Click_Tag", {
    tag: `${selectedMainCategoryName.value}/${selectedSubCategoryName.value}/${costValue}`,
  });
  
  // 更新路由
  await router.push({
    query: {
      ...route.query,
      cost: costValue
    }
  });
  
  // 更新状态
  selectedCost.value = costValue;
  
  // 加载对应应用列表
  appList.value = await fetchAppList(selectedMainCategoryName.value, selectedSubCategoryName.value);
  appListPageCurrent.value = 1;
};

// 二级分类滚动处理
const scrollSubCategoryRight = async () => {
  showLeftArrow.value = true;
  
  if (subCategoryContainer.value) {
    const screenWidth = window.innerWidth;
    subCategoryContainer.value.scrollBy({
      left: screenWidth,
      behavior: "smooth",
    });
    
    // 手动触发一次滚动检查，确保可能需要加载更多
    setTimeout(checkSubCategoryScrollPosition, 300);
  }
};

const scrollSubCategoryLeft = () => {
  if (subCategoryContainer.value) {
    const screenWidth = window.innerWidth;
    subCategoryContainer.value.scrollBy({
      left: -screenWidth,
      behavior: "smooth",
    });
    
    // 更新左箭头显示状态
    setTimeout(() => {
      showLeftArrow.value = subCategoryContainer.value.scrollLeft > 50;
    }, 300);
  }
};

// 滚动事件处理 - 增加防抖
const handleSubCategoryScroll = () => {
  // 清除之前的超时
  if (scrollTimeout) {
    clearTimeout(scrollTimeout);
  }
  
  // 设置新的超时
  scrollTimeout = setTimeout(() => {
    checkSubCategoryScrollPosition();
  }, DEBOUNCE_DELAY);
};

// 检查滚动位置并决定是否加载更多
const checkSubCategoryScrollPosition = () => {
  if (!subCategoryContainer.value) return;
  
  const { scrollLeft, scrollWidth, clientWidth } = subCategoryContainer.value;
  
  // 更新左箭头显示状态
  showLeftArrow.value = scrollLeft > 50;
  
  // 判断是否滚动到接近右边界
  const isNearEnd = scrollLeft + clientWidth >= scrollWidth - SCROLL_BUFFER;
  
  if (isNearEnd) {
    loadMoreSubCategories();
  }
};

// 加载更多数据函数
const loadMoreSubCategories = async () => {
  if (subCategoryLoading.value || !hasMoreSubCategory.value) return;
  
  subCategoryLoading.value = true;
  try {
    subCategoryPageCurrent.value += 1;
    const newData = await fetchSubCategories(
      selectedMainCategoryName.value,
      subCategoryPageCurrent.value,
      SUB_CATEGORY_PAGE_SIZE
    );
    
    if (newData.length > 0) {
      subCategoryList.value = [...subCategoryList.value, ...newData];
      hasMoreSubCategory.value = newData.length >= SUB_CATEGORY_PAGE_SIZE;
    } else {
      hasMoreSubCategory.value = false;
    }
  } catch (error) {
    console.error('加载二级分类数据失败:', error);
    subCategoryPageCurrent.value -= 1;
  } finally {
    subCategoryLoading.value = false;
  }
};

const loadMoreApps = async () => {
  appListPageCurrent.value += 1;
  const newApps = await fetchAppList(
    selectedMainCategoryName.value,
    selectedSubCategoryName.value,
    appListPageCurrent.value
  );
  
  if (newApps.length > 0) {
    appList.value = [...appList.value, ...newApps];
  }
};

// 工具函数
const resetSubCategoryState = () => {
  subCategoryList.value = [];
  subCategoryPageCurrent.value = 1;
  subCategoryLoading.value = false;
  hasMoreSubCategory.value = true;
  showLeftArrow.value = false;
};

// URL生成函数
const { getHomeParams, buildQueryString } = useUrlParams();

const getCategoryUrl = (categoryName) => {
  const queryParams = {
    ...getHomeParams(),
    category: categoryName,
    cost: selectedCost.value,
  };
  return `/?${buildQueryString(queryParams)}`;
};

const getSubCategoryUrl = (mainCategoryName, subCategoryName) => {
  const queryParams = {
    ...getHomeParams(),
    category: mainCategoryName,
    subCategory: subCategoryName,
    cost: selectedCost.value,
  };
  return `/?${buildQueryString(queryParams)}`;
};

const getCostUrl = (costValue) => {
  const queryParams = {
    ...getHomeParams(),
    category: selectedMainCategoryName.value,
    subCategory: selectedSubCategoryName.value,
    cost: costValue,
  };
  return `/?${buildQueryString(queryParams)}`;
};

// 生命周期钩子
onMounted(() => {
  // 客户端额外初始化逻辑
  logEvent("Home_Page_View");
  
  // 初始检查滚动位置
  nextTick(() => {
    checkSubCategoryScrollPosition();
  });
  
  // 设置应用列表无限滚动
  if (bottomObserverPoint.value) {
    appListObserver = new IntersectionObserver(async ([entry]) => {
      if (entry.isIntersecting) {
        await loadMoreApps();
      }
    });
    
    appListObserver.observe(bottomObserverPoint.value);
  }
});

onUnmounted(() => {
  // 清理观察器和超时
  if (appListObserver) {
    appListObserver.disconnect();
  }
  
  if (scrollTimeout) {
    clearTimeout(scrollTimeout);
  }
});

// 路由变化监听
watch(
  () => route.query,
  async (newQuery) => {
    // 当路由参数变化时重新初始化数据
    const { category: newCategory, subCategory: newSubCategory, cost: newCost } = newQuery;
    
    // 更新成本筛选
    if (newCost && newCost !== selectedCost.value) {
      selectedCost.value = newCost;
    }
    
    // 更新一级分类
    if (newCategory && newCategory !== selectedMainCategoryName.value) {
      const mainCategory = mainCategoryList.value.find(cat => cat.name === newCategory);
      if (mainCategory) {
        selectedMainCategoryName.value = newCategory;
        
        // 重置并加载二级分类
        resetSubCategoryState();
        const subCategories = await fetchSubCategories(newCategory);
        subCategoryList.value = subCategories;
        
        // 更新二级分类
        const subCat = subCategories.find(s => s.name === newSubCategory) ? newSubCategory : DEFAULT_SUB_CATEGORY;
        selectedSubCategoryName.value = subCat;
        
        // 加载应用列表
        appList.value = await fetchAppList(newCategory, subCat);
        appListPageCurrent.value = 1;
        
        // 确保DOM更新后检查滚动位置
        nextTick(() => {
          checkSubCategoryScrollPosition();
        });
      }
    } else if (newSubCategory && newSubCategory !== selectedSubCategoryName.value) {
      // 仅更新二级分类
      const subCategoryExists = subCategoryList.value.some(s => s.name === newSubCategory);
      if (subCategoryExists) {
        selectedSubCategoryName.value = newSubCategory;
        appList.value = await fetchAppList(selectedMainCategoryName.value, newSubCategory);
        appListPageCurrent.value = 1;
      }
    }
  },
  { deep: true }
);
</script>

<style scoped>
.text-primary {
  color: var(--primary-color);
}

.border-primary {
  border-color: var(--primary-color);
}

.bg-primary {
  background-color: var(--primary-color);
}

/* 优化移动端滑动体验 */
.sub-category-container {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.sub-category-container::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

/* 加载指示器动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
